package com.dletc.dao.Impl;

import com.dletc.dao.UsersDao;
import com.dletc.domain.Users;
import com.dletc.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;
import java.util.Scanner;

public class UsersDaoImpl implements UsersDao {
    static Scanner scanner = new Scanner(System.in);


    //增加数据
    @Override
    public void inserUser(Users users) {

        try {
            //1.创建一个工具类对象queryRunner
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
            //2.提供sql语句
            String sql = "insert into Users (UserName,PassWord,IsAdmin) values(?,?,?)";
            //3.执行sql语句
            int count = qr.update(sql, users.getUserName(), users.getPassWord(), users.getIsAdmin());

            System.out.println(count > 0?"用户添加成功":"用户添加失败");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    //通过用户名查数据
    @Override
    public Users SelectByUserName(String UserName) {

        Users users = null;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
            String sql = "select * from Users where UserName = ?";
            users = qr.query(sql, new BeanHandler<Users>(Users.class), UserName);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return users;
    }

    @Override
    public Users SelectByID(int UserID) {

        Users users = null;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
            String sql = "select * from Users where UserID = ?";
            users = qr.query(sql, new BeanHandler<Users>(Users.class), UserID);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return users;
    }

    @Override
    public Users SelectByNameAndPassword(String UserName, String PassWord) {


        Users users = null;
        try {
            QueryRunner qr = new QueryRunner(DBUtils.getDataSource());
            String sql = "select * from Users where UserName = ? and PassWord = ?";
            users = qr.query(sql, new BeanHandler<Users>(Users.class), UserName,PassWord);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return users;
    }
}
